/**   
 * @文件名称: IBaseController.java
 * @类路径: cn.common.base
 * @描述: TODO
 * @公司：春城1网
 * @作者：李兴建
 * @时间：2013-9-29 上午11:12:54
 * @版本：V1.0   
 */

package cn.ccew.common.base.controller;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import net.sf.json.util.CycleDetectionStrategy;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.servlet.mvc.SimpleFormController;

import cn.ccew.common.base.model.BaseEntity;
import cn.ccew.common.base.service.IBaseService;
import cn.ccew.common.utils.IEntityMapping;
import cn.ccew.common.utils.Page;

/**
 * @类功能说明：
 * @类修改者：
 * @修改日期：
 * @修改说明：
 * @公司：春城1网
 * @作者：李兴建
 * @创建时间：2013-9-29 上午11:12:54
 * @版本：V1.0
 */

public class BaseController {
	@Autowired
	@Qualifier("baseService")
	protected IBaseService baseService;

	protected Criteria createCriteria(Class<? extends BaseEntity> clazz) throws Exception {
		return this.baseService.createCriteria(clazz);
	}

	/**
	 * 
	 * @param criteria
	 *            在线查询条件
	 * @param queryActionURL
	 *            分页用的Action地址
	 * @param maxPage
	 *            第页显示记录数
	 * @throws Exception
	 */
	public Page queryByPage(Criteria criteria, HttpServletRequest request, int maxPage) throws Exception {
		Page p = new Page();
		if (isParameterExist(request, "pager.offset")) {
			p.setOffset(Integer.parseInt(request.getParameter("pager.offset")));
		}
		criteria.addOrder(Order.desc("lastModifyTime"));
		return this.baseService.findBy(criteria, p.getOffset() + 1, maxPage);
	}

	/**
	 * 响应内容
	 * 
	 * @param content
	 * @throws IOException
	 */
	protected void writerTo(HttpServletResponse response, String content) throws IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");

		// 解决使用代理服务器session重复的问题

		response.setHeader("Pragma ", "no-cache");
		response.setHeader("Cache-Control ", "no-cache");
		response.setDateHeader("Expires ", 0);

		response.getWriter().print(content);
	}

	/**
	 * 成功时写回
	 * 
	 * @param response
	 * @param msg
	 * @throws IOException
	 */
	protected void writerSuccess(HttpServletResponse response, String msg) throws IOException {
		writerTo(response, "{success:true,msg:'" + msg + "'}");
	}
	/**
	 * 成功时写回
	 * 
	 * @param response
	 * @param msg
	 * @throws IOException
	 */
	protected void writerSuccess(HttpServletResponse response, String msg,String jsonInfo) throws IOException {
		writerTo(response, "{success:true,msg:'" + msg + "',info:"+jsonInfo+"}");
	}

	/**
	 * 失败时写回
	 * 
	 * @param response
	 * @param msg
	 * @throws IOException
	 */
	protected void writerFailure(HttpServletResponse response, String msg) throws IOException {
		writerTo(response, "{success:false,msg:'" + msg + "'}");
	}

	/**
	 * 判断参数是否存在
	 * 
	 * @param request
	 * @param key
	 * @return
	 */
	protected boolean isParameterExist(HttpServletRequest request, String key) {
		return request.getParameterMap().containsKey(key);
	}

	/**
	 * 分页封装
	 * 
	 * @param criteria
	 * @param request
	 * @param excludes
	 *            指定过滤哪些字段
	 * @return
	 * @throws IOException
	 */
	protected void responseListJSON(Criteria criteria, HttpServletRequest request, HttpServletResponse response, String[] excludes) throws IOException {
		criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		criteria.setCacheable(true);
		// 设置记录集滚动方式以计算总计条数
		ScrollableResults scrollableResults = null;
		try {
			scrollableResults = criteria.scroll(ScrollMode.SCROLL_SENSITIVE);
			scrollableResults.last();
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 总计记录条数
		int totalCount = scrollableResults.getRowNumber();

		int start = 0;
		int limit = 15;
		try {
			start = Integer.parseInt(request.getParameter("start"));
			limit = Integer.parseInt(request.getParameter("limit"));
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}

		criteria.setFirstResult(start);
		criteria.setFetchSize(limit);
		// 加载
		criteria.setMaxResults(limit);

		criteria.addOrder(Order.desc("lastModifyTime"));

		JsonConfig config = new JsonConfig();
		config.setIgnoreDefaultExcludes(false);
		config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
		config.registerJsonValueProcessor(Long.class, new LongValueProcessor());
		config.registerJsonValueProcessor(int.class, new LongValueProcessor());
		config.registerJsonValueProcessor(Timestamp.class, new TimestampValueProcessor());

		// 只要设置这个数组，指定过滤哪些字段。
		if (null != excludes) {
			config.setExcludes(excludes);
		}

		String listJson = JSONSerializer.toJSON(criteria.list(), config).toString();

		writerTo(response, "{totalProperty:" + totalCount + ",data:" + listJson + "}");
	}

	/**
	 * 分页封装
	 * 
	 * @param criteria
	 * @param request
	 * @param excludes
	 *            指定过滤哪些字段
	 * @return
	 * @throws IOException
	 */
	protected void responseListJSON(Criteria criteria, HttpServletRequest request, HttpServletResponse response, IEntityMapping mapp) throws IOException {
		criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		criteria.setCacheable(true);
		// 设置记录集滚动方式以计算总计条数
		ScrollableResults scrollableResults = null;
		try {
			scrollableResults = criteria.scroll(ScrollMode.SCROLL_SENSITIVE);
			scrollableResults.last();
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 总计记录条数
		int totalCount = scrollableResults.getRowNumber();

		int start = Integer.parseInt(request.getParameter("start"));
		int limit = Integer.parseInt(request.getParameter("limit"));

		criteria.setFirstResult(start);
		criteria.setFetchSize(limit);
		// 加载
		criteria.setMaxResults(limit);

		criteria.addOrder(Order.desc("lastModifyTime"));

		String listJson = JSONSerializer.toJSON(mapp.excute(criteria.list())).toString();

		writerTo(response, "{totalProperty:" + totalCount + ",data:" + listJson + "}");
	}

	protected void responseListJSON(HttpServletResponse response, Map<Object, Object> obj) throws IOException {
		String listJson = JSONSerializer.toJSON(obj).toString();
		writerTo(response, listJson);
	}

	public class LongValueProcessor implements JsonValueProcessor {

		public Object processArrayValue(Object value, JsonConfig jsonConfig) {
			return process(value);
		}

		public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
			return process(value);
		}

		private Object process(Object value) {
			if (null == value) {
				return "";
			}
			return value.toString();
		}
	}

	public class TimestampValueProcessor implements JsonValueProcessor {

		public Object processArrayValue(Object value, JsonConfig jsonConfig) {
			return process(value);
		}

		public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
			return process(value);
		}

		private Object process(Object value) {
			if (null == value) {
				return "";
			}
			Timestamp obj = (Timestamp) value;
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return sdf.format(obj);
		}
	}

}
